﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceCheckIn")]
	public class ConferenceCheckInController : BaseDbController
	{
		private string _importMessage;

		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceCheckIn;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceCheckInModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceCheckInModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from profileHotelInfo in DbContext.ProfileHotelInfo.AsNoTracking().Where(x => x.ConferenceId == model.ConferenceId)
				  join hotelMaster in DbContext.HotelMaster.AsNoTracking().Where(x => x.Status == ConstValues.Status.正常)
				       on profileHotelInfo.HotelId equals hotelMaster.ID
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking().Where(x => x.Status == ConstValues.Status.正常)
				       on profileHotelInfo.ConferenceId equals conferenceMaster.ID
				  select new
				  {
					  Id = profileHotelInfo.ID,
					  Status = profileHotelInfo.Status,
					  OrderNum = profileHotelInfo.OrderNum,
					  DummyRoomNum = profileHotelInfo.DummyRoomNum,
					  HotelName = hotelMaster.HotelName,
					  RoomType = profileHotelInfo.RoomType,
					  IsCombine = profileHotelInfo.IsCombine,
					  Name1 = profileHotelInfo.Name1,
					  Name2 = profileHotelInfo.Name2,
					  CheckinDate = profileHotelInfo.CheckinDate,
					  CheckoutDate = profileHotelInfo.CheckoutDate,
					  Currency = profileHotelInfo.Currency,
					  Fee = profileHotelInfo.Fee,
					  Discount = profileHotelInfo.Discount,
					  Remark = profileHotelInfo.Remark,
					  Contact = profileHotelInfo.Contact,
					  ContactPhone = profileHotelInfo.ContactPhone,
					  ContactMail = profileHotelInfo.ContactMail,
					  CreateDate = profileHotelInfo.CreateDate,
					  Creator = profileHotelInfo.Creator,
					  BenefitStartDate = conferenceMaster.BenefitStartDate,
					  BenefitEndDate = conferenceMaster.BenefitEndDate
				  };

			if (!string.IsNullOrEmpty(model.SelHotelName))
			{
				sql = sql.Where(x => x.HotelName.Contains(model.SelHotelName));
			}
			if (!string.IsNullOrEmpty(model.SelRoomType))
			{
				sql = sql.Where(x => x.RoomType.Contains(model.SelRoomType));
			}
			if (model.SelIsCombine.HasValue)
			{
				sql = sql.Where(x => x.IsCombine == model.SelIsCombine.Value);
			}
			if (!string.IsNullOrEmpty(model.SelFullName))
			{
				sql = sql.Where(x => x.Name1.Contains(model.SelFullName) || x.Name2.Contains(model.SelFullName) || x.Contact.Contains(model.SelFullName));
			}
			if (!string.IsNullOrEmpty(model.SelStatus))
			{
				sql = sql.Where(x => x.Status == model.SelStatus);
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.OrderNum).ThenBy(x => x.DummyRoomNum).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				Id = x.Id,
				Status = x.Status,
				OrderNum = x.OrderNum,
				DummyRoomNum = x.DummyRoomNum,
				HotelName = x.HotelName,
				RoomType = x.RoomType,
				IsCombine = x.IsCombine,
				Name1 = x.Name1,
				Name2 = x.Name2,
				CheckinDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
							x.CheckinDate.ToString("yyyy-MM-dd") :
							x.CheckinDate.ToString("MM/dd/yyyy"),
				CheckoutDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
							x.CheckoutDate.ToString("yyyy-MM-dd") :
							x.CheckoutDate.ToString("MM/dd/yyyy"),
				Currency = x.Currency,
				Price = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee,
				Remark = x.Remark,
				Contact = x.Contact,
				ContactPhone = x.ContactPhone,
				ContactMail = x.ContactMail,
				Creator = x.Creator,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
							x.CreateDate.Value.ToString("yyyy-MM-dd") :
							x.CreateDate.Value.ToString("MM/dd/yyyy"),
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetContactData(int? page, int? rows, string sort, string order, ConferenceCheckInModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.ProfileHotelInfo.AsNoTracking()
					.Where(x => x.ConferenceId == model.ConferenceId)
					.Join(DbContext.ConferenceMaster.AsNoTracking(),
						profileHotelInfo => profileHotelInfo.ConferenceId,
						conferenceMaster => conferenceMaster.ID,
						(profileHotelInfo, conferenceMaster) => new
						{
							OrderNum = profileHotelInfo.OrderNum,
							Status = profileHotelInfo.Status,
							Currency = profileHotelInfo.Currency,
							Fee = profileHotelInfo.Fee,
							Discount = profileHotelInfo.Discount,
							Remark = profileHotelInfo.Remark,
							Contact = profileHotelInfo.Contact,
							ContactPhone = profileHotelInfo.ContactPhone,
							ContactMail = profileHotelInfo.ContactMail,
							BenefitStartDate = conferenceMaster.BenefitStartDate,
							BenefitEndDate = conferenceMaster.BenefitEndDate,
						})
					.GroupBy(x => new
					{
						x.OrderNum,
						x.Status,
						x.Currency,
						x.Remark,
						x.Contact,
						x.ContactPhone,
						x.ContactMail,
						x.BenefitStartDate,
						x.BenefitEndDate,
					})
					.Select(x => new
					{
						OrderNum = x.Key.OrderNum,
						Status = x.Key.Status,
						Currency = x.Key.Currency,
						Remark = x.Key.Remark,
						Contact = x.Key.Contact,
						ContactPhone = x.Key.ContactPhone,
						ContactMail = x.Key.ContactMail,
						BenefitStartDate = x.Key.BenefitStartDate,
						BenefitEndDate = x.Key.BenefitEndDate,
						Fee = x.Sum(y => y.Fee),
						Discount = x.Sum(y => y.Discount),						
					});

			if (!string.IsNullOrEmpty(model.SelName))
			{
				sql = sql.Where(x => x.Contact.Contains(model.SelName));
			}
			if (!string.IsNullOrEmpty(model.SelStatus))
			{
				sql = sql.Where(x => x.Status == model.SelStatus);
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.OrderNum).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				Status = x.Status,
				OrderNum = x.OrderNum,
				Currency = x.Currency,
				Price = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee,
				Remark = x.Remark,
				Contact = x.Contact,
				ContactPhone = x.ContactPhone,
				ContactMail = x.ContactMail,
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<FileResult> Export(string conferenceId, string allId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			var daysCount = 0;
			if (conferenceMaster.CheckinDate.Value.Year == conferenceMaster.CheckoutDate.Value.Year)
			{
				daysCount = conferenceMaster.CheckoutDate.Value.DayOfYear -
						conferenceMaster.CheckinDate.Value.DayOfYear;
			}
			else
			{
				daysCount = conferenceMaster.CheckoutDate.Value.DayOfYear -
						conferenceMaster.CheckinDate.Value.DayOfYear + 365;
			}

			var ids = allId.Split(ConstValues.chrComma);

			DbContext.Database.Connection.Open();
			var command = DbContext.Database.Connection.CreateCommand();
			command.CommandType = System.Data.CommandType.StoredProcedure;
			command.CommandText = "ProcHotelRoomUser";
			command.CommandTimeout = 0;
			command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ConferenceId", conferenceId));
			var result = new List<Dictionary<string, object>>();

			using (var reader = await command.ExecuteReaderAsync())
			{
				object[] values = new object[reader.FieldCount];
				while (await reader.ReadAsync())
				{
					reader.GetValues(values);

					if (!ids.Contains(values[3].ToString()))
					{
						continue;
					}

					Dictionary<string, object> item = new Dictionary<string, object>();
					item.Add("ID", values[0]);
					item.Add("Status", values[1]);
					item.Add("OrderNum", values[2]);
					item.Add("DummyRoomNum", values[3]);
					item.Add("HotelName", values[4]);
					item.Add("RoomType", values[5]);
					item.Add("Currency", values[6]);
					item.Add("Fee", values[7]);
					item.Add("Discount", values[8]);
					item.Add("IsCombine", values[9]);
					item.Add("Name1", values[10]);
					item.Add("Name2", values[11]);
					item.Add("CheckinDate", values[12]);
					item.Add("CheckoutDate", values[13]);
					item.Add("Remark", values[14]);
					item.Add("Contact", values[15]);
					item.Add("ContactPhone", values[16]);
					item.Add("ContactMail", values[17]);
					item.Add("Creator", values[18]);
					item.Add("BenefitStartDate", values[19]);
					item.Add("BenefitEndDate", values[20]);

					for (int index = 0; index < daysCount; index++)
					{
						item.Add("Day" + index.ToString(), Utility.ObjectToInt(values[21 + index]));
					}
					result.Add(item);
				}
			}

			var export = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
				Resources.export_hotelInfoCN : Resources.export_hotelInfoEN;

			XSSFWorkbook workbook;

			using (MemoryStream readStream = new MemoryStream(export))
			{
				workbook = new XSSFWorkbook(readStream);
				ISheet sheet = workbook.GetSheetAt(0);

				var count = 0;

				#region 表头
				IRow row = sheet.CreateRow(count);

				// 订单号
				int column = 0;
				ICell cell = row.CreateCell(column);
				cell.SetCellValue(Resources.OrderNum);

				// 状态
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Status);

				// 虚拟房号
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.DummyRoomNum);

				// 酒店名称
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.HotelName);

				// 房间名称
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Room);

				// 币种
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Currency);

				// 价格
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Price);

				// 拼房
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.IsCombine);

				// 姓名1
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.FullName + 1);

				// 姓名2
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.FullName + 2);

				// 入住时间
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.CheckinDate);

				// 退房时间
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.CheckoutDate);

				for (int index = 0; index < daysCount; index++)
				{
					column++;
					cell = row.CreateCell(column);
					if (Request.Cookies["_culture"].Value == ConstValues.Language.Cn)
					{
						cell.SetCellValue(conferenceMaster.CheckinDate.Value.AddDays(index).ToString("yyyy-MM-dd"));
					}
					else
					{
						cell.SetCellValue(conferenceMaster.CheckinDate.Value.AddDays(index).ToString("MM/dd/yyyy"));
					}
				}

				// 备注
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Remark);

				// 联系人
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Contact);

				// 联系电话
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.ContactPhone);

				// 联系邮箱
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.ContactMail);

				// 创建人
				column++;
				cell = row.CreateCell(column);
				cell.SetCellValue(Resources.Creator);
				#endregion

				foreach (var model in result)
				{
					column = 0;
					count += 1;
					row = sheet.CreateRow(count);

					// 订单号
					column = 0;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["OrderNum"]?.ToString());

					// 状态
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Status"]?.ToString() == ConstValues.Status.已预订 ? Resources.HasBooked : Resources.ScheduleStatusCancel);

					// 虚拟房号
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["DummyRoomNum"]?.ToString());

					// 酒店名称
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["HotelName"]?.ToString());

					// 房间名称
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["RoomType"]?.ToString());

					// 币种
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Currency"]?.ToString());

					// 价格
					column++;
					cell = row.CreateCell(column);
					if (Convert.ToDateTime(model["BenefitStartDate"].ToString())  < DateTime.Now &&
						DateTime.Now < Convert.ToDateTime(model["BenefitEndDate"].ToString()))
					{
						cell.SetCellValue(Utility.ObjectToDouble(model["Discount"]).ToString("N2"));
					}
					else
					{
						cell.SetCellValue(Utility.ObjectToDouble(model["Fee"]).ToString("N2"));
					}

					// 拼房
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["IsCombine"]?.ToString().ToLower() == ConstValues.GenericSelectionType.有 ? Resources.Yes : Resources.No);

					// 姓名1
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Name1"]?.ToString());

					// 姓名2
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Name2"]?.ToString());

					// 入住时间
					column++;
					cell = row.CreateCell(column);
					if (Request.Cookies["_culture"].Value == ConstValues.Language.Cn)
					{
						cell.SetCellValue(Convert.ToDateTime(model["CheckinDate"].ToString()).ToString("yyyy-MM-dd"));
					}
					else
					{
						cell.SetCellValue(Convert.ToDateTime(model["CheckinDate"].ToString()).ToString("MM/dd/yyyy"));
					}

					// 退房时间
					column++;
					cell = row.CreateCell(column);
					if (Request.Cookies["_culture"].Value == ConstValues.Language.Cn)
					{
						cell.SetCellValue(Convert.ToDateTime(model["CheckoutDate"].ToString()).ToString("yyyy-MM-dd"));
					}
					else
					{
						cell.SetCellValue(Convert.ToDateTime(model["CheckoutDate"].ToString()).ToString("MM/dd/yyyy"));
					}

					for (int index = 0; index < daysCount; index++)
					{
						column++;
						cell = row.CreateCell(column);
						cell.SetCellValue(model["Day" + index.ToString()]?.ToString());
					}

					// 备注
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Remark"]?.ToString());

					// 联系人
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Contact"]?.ToString());

					// 联系电话
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["ContactPhone"]?.ToString());

					// 联系邮箱
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["ContactMail"]?.ToString());

					// 创建人
					column++;
					cell = row.CreateCell(column);
					cell.SetCellValue(model["Creator"]?.ToString());
				}
			}

			MemoryStream exportStream = new MemoryStream();
			workbook.Write(exportStream);
			exportStream.Flush();
			exportStream.Position = 0;

			return File(exportStream, Application.Octet,
					$"export_hotelInfo_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
		}
		
		[Route("DownloadImportTemplate/{conferenceId}")]
		public async Task<ActionResult> DownloadImportTemplate(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == conferenceId);

			if (conferenceMaster.IsInternational)
			{
				return File(Resources.import_hotelInfoEN,
						"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
						$"import_hotelInfoEN.xlsx");
			}
			else
			{
				return File(Resources.import_hotelInfoCN,
						"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
						$"import_hotelInfoCN.xlsx");
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Import/{ConferenceId}")]
		public async Task<JsonResult> Import(ConferenceCheckInModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			if (model.ImportFile != null && model.ImportFile.InputStream.Length > 0)
			{
				try
				{
					var result = await this.ImportData(model.ConferenceId, model.ImportFile.InputStream);

					if (!string.IsNullOrEmpty(_importMessage))
					{
						return JsonCamelCase(Utility.CreateFailJsonResult(_importMessage),
								JsonRequestBehavior.AllowGet, true);
					}
					else
					{
						return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessImport),
								JsonRequestBehavior.AllowGet, true);
					}
				}
				catch (Exception)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgFileError),
							JsonRequestBehavior.AllowGet, true);
				}
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgInvalidFile),
					JsonRequestBehavior.AllowGet, true);
			}
		}

		private async Task<int> ImportData(string conferenceId, Stream stream)
		{
			var conferenceInfo = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == conferenceId);

			XSSFWorkbook workbook;
			workbook = new XSSFWorkbook(stream);

			ISheet sheet = workbook.GetSheetAt(0);
			int rowIndex = 0;
			int recordCount = 0;

			while (true)
			{
				var tmpMsg = string.Empty;
				var list = new List<int>();
				try
				{
					rowIndex++;
					IRow row = sheet.GetRow(rowIndex);
					if (row == null)
					{
						break;
					}

					var model = new ConferenceCheckInModel()
					{
						ConferenceId = conferenceId
					};
					int columnIndex = 0;

					// 酒店名称
					model.HotelName = Utility.ReadExcelField(row.GetCell(columnIndex));
					if (string.IsNullOrEmpty(model.HotelName))
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}
					else if (model.HotelName.Length > 100)
					{
						tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.HotelName, 100) + "<br/>";
					}
					else
					{
						var hotelMaster = await DbContext.HotelMaster.AsNoTracking()
								.FirstOrDefaultAsync(x => x.ConferenceId == conferenceId &&
									x.HotelName == model.HotelName);

						if (hotelMaster == null)
						{
							tmpMsg += Resources.MsgHotelTypeError + "<br/>";
							//tmpMsg += string.Format(Resources.MsgImportNotExist, model.HotelName, Resources.HotelName) + "<br/>";
						}
						else
						{
							model.HotelId = hotelMaster.ID;
						}
					}
					model.HotelName = model.HotelName.Replace(ConstValues.strHtmlEnter, string.Empty).Replace(ConstValues.strHtmlChengeLine, string.Empty);

					// 房间名称
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.RoomType = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (string.IsNullOrEmpty(model.RoomType))
						{
							tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
						}
						if (model.RoomType.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.RoomType, 100) + "<br/>";
						}
					}else
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}

					// 币种
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Currency = Utility.ReadExcelField(row.GetCell(columnIndex));
						
						if (string.IsNullOrEmpty(model.Currency))
						{
							tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
						}
						if (model.Currency.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.Currency, Resources.Currency, 100) + "<br/>";
						}

						if (model.Currency != ConstValues.Currency.人民币 && model.Currency != ConstValues.Currency.美元 &&
									model.Currency != ConstValues.Currency.全角人民币)
						{
							tmpMsg += Resources.MsgImportRightCurrency + "<br/>";
						}

						if (model.Currency == ConstValues.Currency.全角人民币)
						{
							model.Currency = ConstValues.Currency.人民币;
						}
					}
					else
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}

					// 拼房
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Combine = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Combine.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.IsCombine, 100) + "<br/>";
						}

						if (model.Combine == Resources.Yes)
						{
							model.IsCombine = true;
						}
						else
						{
							model.IsCombine = false;
						}
					}

					// 姓名1
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Name1 = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (string.IsNullOrEmpty(model.Name1))
						{
							tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
						}
						if (model.Name1.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.FullName + 1, 100) + "<br/>";
						}
					}
					else
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}

					// 姓名2
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Name2 = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Name2.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.FullName + 2, 100) + "<br/>";
						}
					}

					// 入住时间
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Checkin = Utility.ReadExcelField(row.GetCell(columnIndex));
						
						if (string.IsNullOrEmpty(model.Checkin))
						{
							tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
						}
						var tmp = new DateTime();
						if (DateTime.TryParse(model.Checkin, out tmp))
						{
							model.CheckinDate = tmp;
						}
						else
						{
							tmpMsg += string.Format(Resources.MsgImportNotExist, model.HotelName, Resources.CheckinDate) + "<br/>";
						}
					}
					else
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}

					// 离开时间
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Checkout = Utility.ReadExcelField(row.GetCell(columnIndex));
						
						if (string.IsNullOrEmpty(model.Checkout))
						{
							tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
						}
						var tmp = new DateTime();
						if (DateTime.TryParse(model.Checkout, out tmp))
						{
							model.CheckoutDate = tmp;
						}
						else
						{
							tmpMsg += string.Format(Resources.MsgImportNotExist, model.HotelName, Resources.CheckoutDate) + "<br/>";
						}
					}
					else
					{
						tmpMsg += Resources.MsgImportHasEmpty + "<br/>";
					}

					// 备注
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Remark = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Remark.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.Remark, 100) + "<br/>";
						}
					}

					// 联系人
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.Contact = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Contact.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.Contact, 100) + "<br/>";
						}
					}

					// 联系电话
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.ContactPhone = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Contact.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.ContactPhone, 100) + "<br/>";
						}
					}

					// 联系邮箱
					columnIndex++;
					if (row.GetCell(columnIndex) != null)
					{
						model.ContactMail = Utility.ReadExcelField(row.GetCell(columnIndex));

						if (model.Contact.Length > 100)
						{
							tmpMsg += string.Format(Resources.MsgImportMaxLength, model.HotelName, Resources.ContactMail, 100) + "<br/>";
						}
					}				

					if (!string.IsNullOrEmpty(tmpMsg))
					{
						_importMessage += tmpMsg;
						continue;
					}

					using (var transaction = DbContext.Database.BeginTransaction())
					{
						var roomMaster = DbContext.RoomMaster.AsNoTracking()
							.Where(x => x.Status == ConstValues.Status.正常 &&
								x.HotelId == model.HotelId &&
								x.RoomType == model.RoomType)
							.ToList();
						var isTrue = true;
						var daysCount = 0;
						if (model.CheckinDate.Year == model.CheckoutDate.Year)
						{
							daysCount = model.CheckoutDate.DayOfYear -
									model.CheckinDate.DayOfYear;
						}
						else
						{
							daysCount = model.CheckoutDate.DayOfYear -
									model.CheckinDate.DayOfYear + 365;
						}

						var tempRoom = roomMaster.FirstOrDefault(x => x.BookDate == model.CheckinDate && x.Currency == model.Currency);
						if (tempRoom == null)
						{
							_importMessage += Resources.MsgRoomTypeError + "<br/>";
							//_importMessage +=string.Format(Resources.MsgImportNotExist, model.CheckinDate.ToString("yyyy-MM-dd")+model.HotelName, model.RoomType) + "<br/>";
							isTrue = false;
							continue;
						}
						var dummyRoomNumList = Utility.GetDummyRoomNum(model.ConferenceId, 1, list);
						var profileHotelInfo = new ProfileHotelInfo
						{
							ID = Utility.GetTableId(ConstValues.TableName.ProfileHotelInfo),
							UserName = LoginUser.UserName,
							ConferenceId = model.ConferenceId,
							HotelId = model.HotelId,
							RoomType = model.RoomType,
							RoomId = string.Empty,
							IsCombine = model.IsCombine,
							Name1 = model.Name1,
							Name2 = model.Name2,
							CheckinDate = model.CheckinDate,
							CheckoutDate = model.CheckoutDate,
							Remark = model.Remark,
							Contact = model.Contact,
							ContactPhone = model.ContactPhone,
							ContactMail = model.ContactMail,
							Fee = tempRoom.Price1.Value * daysCount,
							Discount = tempRoom.Price2.Value * daysCount,
							Currency = tempRoom.Currency,
							OrderNum = Utility.GetOrderNum(model.ConferenceId, ConstValues.OrderType.酒店),
							DummyRoomNum = dummyRoomNumList[0],
							Status = ConstValues.Status.已预订,
							Creator = LoginUser.UserName,
							CreateIP = LoginUser.IP,
							CreateDate = DateTime.Now
						};
						DbContext.ProfileHotelInfo.Add(profileHotelInfo);

						for (var index = 0; index < daysCount; index++)
						{
							var checkinDate = model.CheckinDate.AddDays(index);

							var room = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == model.HotelId && y.RoomType == model.RoomType &&
										y.BookDate == checkinDate && y.Currency == model.Currency);
							if (room == null || room.LeftBedCount.Value - room.RoomBedCount < 0)
							{
								_importMessage += "【" + checkinDate.ToString("yyyy-MM-dd") + "】" + string.Format(Resources.MsgNotEnoughBed, model.HotelName, model.RoomType) + "<br/>";
								isTrue = false;
								break;
							}

							if (room == null || room.LeftRoomCount.Value - 1 < 0)
							{
								_importMessage += "【" + checkinDate.ToString("yyyy-MM-dd") + "】" + string.Format(Resources.MsgNotEnoughRoom, model.HotelName, model.RoomType) + "<br/>";
								isTrue = false;
								break;
							}

							var roomTypeId = roomMaster.FirstOrDefault(x => x.BookDate == checkinDate).ID;
							var checkinInfo = new CheckinInfo
							{
								ID = Utility.GetTableId(ConstValues.TableName.CheckinInfo),
								ConferenceId = model.ConferenceId,
								AttendenceId = profileHotelInfo.ID,
								HotelId = model.HotelId,
								RoomTypeId = roomTypeId,
								CheckinDate = checkinDate,
								Creator = LoginUser.UserName,
								CreateIP = LoginUser.IP,
								CreateDate = DateTime.Now,
								UserName = LoginUser.UserName,
							};
							DbContext.CheckinInfo.Add(checkinInfo);

							if (!string.IsNullOrEmpty(model.Name1) && !string.IsNullOrEmpty(model.Name2))
							{
								room.LeftRoomCount = room.LeftRoomCount.Value - 1;
								room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
							}
							else
							//只填了一个名字
							{
								//需要拼房
								if (model.IsCombine)
								{
									//床位数为1,即大床房
									if (room.RoomBedCount % 2 != 0)
									{
										room.LeftRoomCount = room.LeftRoomCount.Value - 1;
										room.LeftBedCount = room.LeftBedCount.Value - 1;
									}
									else
									{
										//剩余床位数为偶数
										if (room.LeftBedCount.Value % 2 == 0)
										{
											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
										else
										{
											room.LeftRoomCount = room.LeftRoomCount.Value - 1;
											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
									}
								}
								else
								{
									room.LeftRoomCount = room.LeftRoomCount.Value - 1;
									room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
								}
							}
							room.Updater = LoginUser.UserName;
							room.UpdateDate = DateTime.Now;
							room.UpdateIP = LoginUser.IP;
						}

						await DbContext.SaveChangesAsync();
						if (isTrue)
						{
							transaction.Commit();
						}
					}

					recordCount++;
				}
				catch (Exception)
				{
					continue;
				}
			}

			return await Task.FromResult(recordCount);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("SetBooking/{ConferenceId}")]
		public async Task<JsonResult> SetBooking(ProfileHotelModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);


			var result = await DbContext.ProfileHotelInfo
					.FirstOrDefaultAsync(x => x.ID == model.ProfileHotelId);

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					result.Status = ConstValues.Status.已预订;

					DateTime tempCheckinDate = result.CheckinDate;
					DateTime tempCheckoutDate = result.CheckoutDate;
					while (tempCheckinDate < tempCheckoutDate)
					{
						//把房间减掉
						var room = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == result.HotelId && y.RoomType == result.RoomType &&
									y.BookDate == tempCheckinDate && y.Currency == result.Currency);
						if (room != null)
						{
							if (result.IsCombine)
							{
								//需要拼房
								if (!string.IsNullOrEmpty(result.Name1) && !string.IsNullOrEmpty(result.Name2))
								{
									//如果填了两个名字
									room.LeftRoomCount = room.LeftRoomCount.Value - 1;
									room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
								}
								else
								{
									if (room.LeftBedCount.Value % 2 == 1)
									{
										room.LeftRoomCount -= 1;
									}
									room.LeftBedCount -= 1;
								}
							}
							else
							{
								//不需要拼房
								room.LeftRoomCount -= 1;
								room.LeftBedCount -= room.RoomBedCount.Value;
							}
						}else
						{
							return JsonCamelCase(Utility.CreateFailJsonResult(
										string.Format(Resources.MsgNotEnoughBookingRoom, tempCheckinDate.ToString("yyyy-MM-dd"), result.RoomType)),
									JsonRequestBehavior.AllowGet);
						}

						#region CheckInInfo
						var checkinInfo = new CheckinInfo
						{
							ID = Utility.GetTableId(ConstValues.TableName.CheckinInfo),
							ConferenceId = model.ConferenceId,
							AttendenceId = result.ID,
							HotelId = result.HotelId,
							RoomTypeId = room.ID,
							CheckinDate = tempCheckinDate,
							Creator = LoginUser.UserName,
							CreateDate = DateTime.Now,
							CreateIP = LoginUser.IP,
							UserName = LoginUser.UserName,
						};
						DbContext.CheckinInfo.Add(checkinInfo);
						#endregion

						tempCheckinDate = tempCheckinDate.AddDays(1);
					}
					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessBooking),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("AddHotel/{ConferenceId}")]
		public async Task<JsonResult> AddHotel(ProfileHotelModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var errorHotelName = string.Empty;
			var errorRoomTypeName = string.Empty;
			var errorDate = string.Empty;
			var totalList = model.TotalList;
			var isTrue = true;
			var orderNum = model.OrderNumber;
			List<int> dummyList = new List<int>();
			using (var transaction = DbContext.Database.BeginTransaction())
			{
				totalList.ForEach(x =>
				{
					var hotelId = x.HotelId;
					var currency = x.Currency;
					var roomMaster = DbContext.RoomMaster.AsNoTracking().FirstOrDefault(y => y.RoomType == x.RoomTypeId && y.HotelId == x.HotelId);
					var roomId = "";

					dummyList = Utility.GetDummyRoomNum(model.ConferenceId, x.nameList.Count(), dummyList);
					int dummyIndex = 0;

					//由多组两个名字组成的list
					x.nameList.ForEach(z =>
					{
						int differenceInDays = (Convert.ToDateTime(x.CheckoutDate) - Convert.ToDateTime(x.CheckinDate)).Days;
						#region ProfileHotelInfo
						var profileHotelInfo = new ProfileHotelInfo
						{
							ID = Utility.GetTableId(ConstValues.TableName.ProfileHotelInfo),
							ConferenceId = x.ConferenceId,
							HotelId = hotelId,
							RoomType = roomMaster.RoomType,
							RoomId = string.Empty,
							IsCombine = x.NeedCombine == "true" ? true : false,
							Name1 = string.IsNullOrEmpty(z[0]) ? string.Empty : z[0].Trim(),
							Name2 = string.IsNullOrEmpty(z[1]) ? string.Empty : z[1].Trim(),
							CheckinDate = Convert.ToDateTime(x.CheckinDate),
							CheckoutDate = Convert.ToDateTime(x.CheckoutDate),
							OrderNum = orderNum,
							DummyRoomNum = dummyList[dummyIndex],
							Contact = x.ContactName,
							ContactPhone = x.ContactMobile,
							ContactMail = x.ContactMail,
							Remark = x.Remark,
							Currency = x.Currency,
							Fee = roomMaster.Price1.Value * differenceInDays,
							Discount = roomMaster.Price2.Value * differenceInDays,
							Creator = LoginUser.UserName,
							CreateDate = DateTime.Now,
							CreateIP = LoginUser.IP,
							UserName = LoginUser.UserName,
							Status = ConstValues.Status.已预订
						};
						DbContext.ProfileHotelInfo.Add(profileHotelInfo);
						#endregion
						dummyIndex++;
						DateTime startDate = Convert.ToDateTime(x.CheckinDate);
						DateTime endDate = Convert.ToDateTime(x.CheckoutDate);
						while (isTrue && startDate < endDate)
						{
							var room = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == hotelId && y.RoomType == roomMaster.RoomType &&
										y.BookDate == startDate && y.Currency == currency);
							if (room == null || room.LeftRoomCount.Value < Convert.ToInt32(x.RoomNumber) || room.LeftBedCount < Convert.ToInt32(x.CheckinNumber))
							{
								isTrue = false;
								errorHotelName = DbContext.HotelMaster.AsNoTracking().FirstOrDefault(y => y.ID == hotelId)?.HotelName;
								errorRoomTypeName = roomMaster.RoomType;
								errorDate = startDate.ToString("yyyy-MM-dd");
								break;
							}

							roomId = room.ID;

							//如果填了两个名字
							if (!string.IsNullOrEmpty(z[0]) && !string.IsNullOrEmpty(z[1]))
							{
								room.LeftRoomCount = room.LeftRoomCount.Value - 1;
								room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
							}
							else
							//只填了一个名字
							{
								//需要拼房
								if (x.NeedCombine == "true")
								{
									//床位数为1,即大床房
									if (room.RoomBedCount % 2 != 0)
									{
										room.LeftRoomCount = room.LeftRoomCount.Value - 1;
										room.LeftBedCount = room.LeftBedCount.Value - 1;
									}
									else
									{
										//剩余床位数为偶数
										if (room.LeftBedCount.Value % 2 == 0)
										{

											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
										else
										{
											room.LeftRoomCount = room.LeftRoomCount.Value - 1;
											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
									}
								}
								else
								{
									room.LeftRoomCount = room.LeftRoomCount.Value - 1;
									room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
								}
							}
							room.Updater = LoginUser.UserName;
							room.UpdateDate = DateTime.Now;
							room.UpdateIP = LoginUser.IP;

							#region CheckInInfo
							var checkinInfo = new CheckinInfo
							{
								ID = Utility.GetTableId(ConstValues.TableName.CheckinInfo),
								ConferenceId = x.ConferenceId,
								AttendenceId = profileHotelInfo.ID,
								HotelId = x.HotelId,
								RoomTypeId = room.ID,
								CheckinDate = startDate,
								Creator = LoginUser.UserName,
								CreateDate = DateTime.Now,
								CreateIP = LoginUser.IP,
								UserName = LoginUser.UserName,
							};
							DbContext.CheckinInfo.Add(checkinInfo);
							#endregion

							startDate = startDate.AddDays(1);
						}
					});
				});
				await DbContext.SaveChangesAsync();

				if (isTrue)
				{
					transaction.Commit();
				}
			}

			if (isTrue)
			{
				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						"【" + errorDate + "】" + string.Format(Resources.MsgNotEnoughRoom, errorHotelName, errorRoomTypeName)),
					JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("EditHotel/{ConferenceId}")]
		public async Task<JsonResult> EditHotel(ProfileHotelModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var errorHotelName = string.Empty;
			var errorRoomTypeName = string.Empty;
			var errorDate = string.Empty;
			var totalList = model.TotalList;
			var isTrue = true;
			var orderNum = model.OrderNumber;
			List<int> dummyList = new List<int>();
			using (var transaction = DbContext.Database.BeginTransaction())
			{
				totalList.ForEach(x =>
				{
					var hotelId = x.HotelId;
					var currency = x.Currency;
					var roomMaster = DbContext.RoomMaster.AsNoTracking().FirstOrDefault(y => y.RoomType == x.RoomTypeId && y.HotelId == x.HotelId);
					var roomId = "";

					//由多组两个名字组成的list
					x.nameList.ForEach(z =>
					{
						int differenceInDays = (Convert.ToDateTime(x.CheckoutDate) - Convert.ToDateTime(x.CheckinDate)).Days;
						var profileHotelInfo = DbContext.ProfileHotelInfo.FirstOrDefault(y => y.ID == model.ProfileHotelId);


						DateTime tempCheckinDate = profileHotelInfo.CheckinDate;
						DateTime tempCheckoutDate = profileHotelInfo.CheckoutDate;
						while (tempCheckinDate < tempCheckoutDate)
						{
							//先把房间加回去
							var oldroom = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == profileHotelInfo.HotelId && y.RoomType == profileHotelInfo.RoomType &&
										y.BookDate == tempCheckinDate && y.Currency == profileHotelInfo.Currency);
							if (oldroom != null)
							{
								if (profileHotelInfo.IsCombine)
								{
									//需要拼房
									if (!string.IsNullOrEmpty(profileHotelInfo.Name1) && !string.IsNullOrEmpty(profileHotelInfo.Name2))
									{
										//如果填了两个名字
										oldroom.LeftRoomCount = oldroom.LeftRoomCount.Value + 1;
										oldroom.LeftBedCount = oldroom.LeftBedCount.Value + oldroom.RoomBedCount.Value;
									}
									else
									{
										if (oldroom.LeftBedCount.Value % 2 == 0)
										{
											oldroom.LeftRoomCount += 1;
										}
										oldroom.LeftBedCount += 1;
									}
								}
								else
								{
									//不需要拼房
									oldroom.LeftRoomCount += 1;
									oldroom.LeftBedCount += oldroom.RoomBedCount.Value;
								}
							}
							tempCheckinDate = tempCheckinDate.AddDays(1);
						}
						//再把checkininfo的原有数据删掉
						var oldCheckinInfoList = DbContext.CheckinInfo.Where(y => y.AttendenceId == profileHotelInfo.ID).ToList();
						DbContext.CheckinInfo.RemoveRange(oldCheckinInfoList);

						//然后再把数据插回去
						DateTime startDate = Convert.ToDateTime(x.CheckinDate);
						DateTime endDate = Convert.ToDateTime(x.CheckoutDate);
						while (isTrue && startDate < endDate)
						{

							var room = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == hotelId && y.RoomType == roomMaster.RoomType &&
										y.BookDate == startDate && y.Currency == currency);
							if (room == null || room.LeftRoomCount.Value < Convert.ToInt32(x.RoomNumber) || room.LeftBedCount < Convert.ToInt32(x.CheckinNumber))
							{
								isTrue = false;
								errorHotelName = DbContext.HotelMaster.AsNoTracking().FirstOrDefault(y => y.ID == hotelId)?.HotelName;
								errorRoomTypeName = roomMaster.RoomType;
								errorDate = startDate.ToString("yyyy-MM-dd");
								break;
							}

							roomId = room.ID;

							//如果填了两个名字
							if (!string.IsNullOrEmpty(z[0]) && !string.IsNullOrEmpty(z[1]))
							{
								room.LeftRoomCount = room.LeftRoomCount.Value - 1;
								room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
							}
							else
							//只填了一个名字
							{
								//需要拼房
								if (x.NeedCombine == "true")
								{
									//床位数为1,即大床房
									if (room.RoomBedCount % 2 != 0)
									{
										room.LeftRoomCount = room.LeftRoomCount.Value - 1;
										room.LeftBedCount = room.LeftBedCount.Value - 1;
									}
									else
									{
										//剩余床位数为偶数
										if (room.LeftBedCount.Value % 2 == 0)
										{

											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
										else
										{
											room.LeftRoomCount = room.LeftRoomCount.Value - 1;
											room.LeftBedCount = room.LeftBedCount.Value - 1;
										}
									}
								}
								else
								{
									room.LeftRoomCount = room.LeftRoomCount.Value - 1;
									room.LeftBedCount = room.LeftBedCount.Value - room.RoomBedCount.Value;
								}
							}
							room.Updater = LoginUser.UserName;
							room.UpdateDate = DateTime.Now;
							room.UpdateIP = LoginUser.IP;

							#region CheckInInfo
							var checkinInfo = new CheckinInfo
							{
								ID = Utility.GetTableId(ConstValues.TableName.CheckinInfo),
								ConferenceId = x.ConferenceId,
								AttendenceId = profileHotelInfo.ID,
								HotelId = x.HotelId,
								RoomTypeId = room.ID,
								CheckinDate = startDate,
								Creator = LoginUser.UserName,
								CreateDate = DateTime.Now,
								CreateIP = LoginUser.IP,
								UserName = LoginUser.UserName,
							};
							DbContext.CheckinInfo.Add(checkinInfo);
							#endregion

							startDate = startDate.AddDays(1);
						}

						//最后更新profile表的数据
						#region ProfileHotelInfo
						profileHotelInfo.HotelId = hotelId;
						profileHotelInfo.RoomType = roomMaster.RoomType;
						profileHotelInfo.RoomId = string.Empty;
						profileHotelInfo.IsCombine = x.NeedCombine == "true" ? true : false;
						profileHotelInfo.Name1 = string.IsNullOrEmpty(z[0]) ? string.Empty : z[0].Trim();
						profileHotelInfo.Name2 = string.IsNullOrEmpty(z[1]) ? string.Empty : z[1].Trim();
						profileHotelInfo.CheckinDate = Convert.ToDateTime(x.CheckinDate);
						profileHotelInfo.CheckoutDate = Convert.ToDateTime(x.CheckoutDate);
						profileHotelInfo.Currency = x.Currency;
						profileHotelInfo.Fee = roomMaster.Price1.Value * differenceInDays;
						profileHotelInfo.Discount = roomMaster.Price2.Value * differenceInDays;
						profileHotelInfo.UserName = LoginUser.UserName;
						profileHotelInfo.Status = ConstValues.Status.已预订;
						profileHotelInfo.Contact = x.ContactName.Trim();
						profileHotelInfo.ContactMail = x.ContactMail.Trim();
						profileHotelInfo.ContactPhone = x.ContactMobile.Trim();
						profileHotelInfo.Remark = string.IsNullOrEmpty(x.Remark) ? string.Empty : x.Remark.Trim();

						#endregion
					});
				});
				await DbContext.SaveChangesAsync();

				if (isTrue)
				{
					transaction.Commit();
				}
			}

			if (isTrue)
			{
				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						"【" + errorDate + "】" + string.Format(Resources.MsgNotEnoughRoom, errorHotelName, errorRoomTypeName)),
					JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("CancelBooking/{ConferenceId}")]
		public async Task<JsonResult> CancelBooking(ProfileHotelModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);
			
			var result = await DbContext.ProfileHotelInfo
					.FirstOrDefaultAsync(x => x.ID == model.ProfileHotelId);

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					result.Status = ConstValues.Status.已取消;

					var oldCheckinInfoList = DbContext.CheckinInfo.Where(y => y.AttendenceId == model.ProfileHotelId).ToList();
					DbContext.CheckinInfo.RemoveRange(oldCheckinInfoList);

					DateTime tempCheckinDate = result.CheckinDate;
					DateTime tempCheckoutDate = result.CheckoutDate;
					while (tempCheckinDate < tempCheckoutDate)
					{
						//把房间加回去
						var oldroom = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == result.HotelId && y.RoomType == result.RoomType &&
									y.BookDate == tempCheckinDate && y.Currency == result.Currency);
						if (oldroom != null)
						{
							if (result.IsCombine)
							{
								//需要拼房
								if (!string.IsNullOrEmpty(result.Name1) && !string.IsNullOrEmpty(result.Name2))
								{
									//如果填了两个名字
									oldroom.LeftRoomCount = oldroom.LeftRoomCount.Value + 1;
									oldroom.LeftBedCount = oldroom.LeftBedCount.Value + oldroom.RoomBedCount.Value;
								}
								else
								{
									if (oldroom.LeftBedCount.Value % 2 == 0)
									{
										oldroom.LeftRoomCount += 1;
									}
									oldroom.LeftBedCount += 1;
								}
							}
							else
							{
								//不需要拼房
								oldroom.LeftRoomCount += 1;
								oldroom.LeftBedCount += oldroom.RoomBedCount.Value;
							}
						}
						tempCheckinDate = tempCheckinDate.AddDays(1);
					}
					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessCancel),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("DeleteBooking/{ConferenceId}")]
		public async Task<JsonResult> DeleteBooking(ProfileHotelModel model) {
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ProfileHotelInfo
					.FirstOrDefaultAsync(x => x.ID == model.ProfileHotelId);

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					result.Status = ConstValues.Status.已取消;

					var oldCheckinInfoList = DbContext.CheckinInfo.Where(y => y.AttendenceId == model.ProfileHotelId).ToList();
					DbContext.CheckinInfo.RemoveRange(oldCheckinInfoList);

					DateTime tempCheckinDate = result.CheckinDate;
					DateTime tempCheckoutDate = result.CheckoutDate;
					while (tempCheckinDate < tempCheckoutDate)
					{
						//把房间加回去
						var oldroom = DbContext.RoomMaster.FirstOrDefault(y => y.HotelId == result.HotelId && y.RoomType == result.RoomType &&
									y.BookDate == tempCheckinDate && y.Currency == result.Currency);
						if (oldroom != null)
						{
							if (result.IsCombine)
							{
								//需要拼房
								if (!string.IsNullOrEmpty(result.Name1) && !string.IsNullOrEmpty(result.Name2))
								{
									//如果填了两个名字
									oldroom.LeftRoomCount = oldroom.LeftRoomCount.Value + 1;
									oldroom.LeftBedCount = oldroom.LeftBedCount.Value + oldroom.RoomBedCount.Value;
								}
								else
								{
									if (oldroom.LeftBedCount.Value % 2 == 0)
									{
										oldroom.LeftRoomCount += 1;
									}
									oldroom.LeftBedCount += 1;
								}
							}
							else
							{
								//不需要拼房
								oldroom.LeftRoomCount += 1;
								oldroom.LeftBedCount += oldroom.RoomBedCount.Value;
							}
						}
						tempCheckinDate = tempCheckinDate.AddDays(1);
					}

					//DbContext.ProfileHotelInfo.Remove(result);

					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				//删除预定
				DbContext.ProfileHotelInfo.Remove(result);
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}
	}
}